<?php
class User_model extends CI_Model{
	function __construct(){
		parent::__construct();
	}

	public function login(){
		// grab user input
		$username = $this->security->xss_clean($this->input->post('username'));
		$password = $this->security->xss_clean(hash ('sha256', $this->input->post('password')));

		// Prep the query
		$this->db->where('user_name', $username);
		$this->db->where('user_password', $password);

		// Run the query
		$query = $this->db->get('user');
		// Let's check if there are any results
		if($query->num_rows() == 1)
		{
			// If there is a user, then create session data
			$row = $query->row();
			$data = array(
					'user_id' => $row->user_id,
					'user_name' => $row->user_name,
					'validated' => true
			);
			$this->session->set_userdata($data);
			return true;
		}
		// If the previous process did not validate
		// then return false.
		return false;
	}
	
	public function authenticate($username, $password){

		$this->db->where('user_name', $username);
		$this->db->where('user_password', $password);
		$query = $this->db->get('user');
		if($query->num_rows() == 1)
		{
			return true;
		}
		return false;
	}
	

	public function validate(){

		$username = $this->security->xss_clean($this->input->post('username'));
		$password = $this->security->xss_clean(hash ('sha256', $this->input->post('password')));

		$this->db->where('user_name', $username);
		$this->db->where('user_password', $password);

		$query = $this->db->get('user');
		if($query->num_rows() == 1)
			return true;
		return false;
	}

	public function user_name_exist($username){
		$this->db->where('user_name', $username);
		$query = $this->db->get('user');
		if($query->num_rows() == 1)
			return true;
		return false;
	}


	public function update(){
		$username = $this->security->xss_clean($this->input->post('username'));
		$new_password = $this->security->xss_clean(hash ('sha256', $this->input->post('new_password')));

		$this->db->where('user_name', $username);

		$data = array(
				'user_name' => $username ,
				'user_password' => $new_password
		);
		if ($this->db->update('user', $data)){
			return true;
		}else
			return false;
	}

	public function create(){
		$username = $this->security->xss_clean($this->input->post('create_username'));
		$password = $this->security->xss_clean(hash ('sha256', $this->input->post('create_password')));

		$data = array(
				'user_name' => $username ,
				'user_password' => $password
		);
		if ($this->db->insert('user', $data)){
			return true;
		}
		return false;
	}


}